package cn.edu.zafu.bigdata.x.bd121;

import java.util.InputMismatchException;
import java.util.Random;
import java.util.Scanner;

/**
 * 猜数字小游戏
 *
 * @author 202211090121
 */
public class GuessNum {

    /**
     * 最大猜测次数
     */
    private static final int MAX_GUESS = 10;

    public static void main(String[] args) {
        // 生成一个1-100的随机数
        Random random = new Random();
        int num = random.nextInt(100) + 1;
        //记录玩家猜的次数
        int count = 0;

        while (count < MAX_GUESS) {
            // 玩家输入一个数字
            int guessNum;
            while (true) {
                System.out.print("请输入一个0-100之间的数字：");
                try {
                    Scanner sc = new Scanner(System.in);
                    guessNum = sc.nextInt();
                    if (guessNum < 1 || guessNum > 100) {
                        System.out.println("输入的数字不在1-100之间，请重新输入！");
                        continue;
                    }
                    break;
                } catch (InputMismatchException e) {
                    System.out.println("输入的不是数字，请重新输入！");
                } catch (Exception e) {
                    System.out.println("系统异常，请重新输入！");
                }
            }
            count += 1;
            if (guessNum < num) {
                System.out.println("猜小了，请再试一次！");
            } else if (guessNum > num) {
                System.out.println("猜大了，请再试一次！");
            } else {
                System.out.println("恭喜你，猜对了！");
                break;
            }
        }
        if (count > MAX_GUESS) {
            System.out.println("你猜错太多次了");
        }
        System.out.println("游戏结束！");
    }
}
